package com.sgb.kjwl.view.ui.fragment.home;

import android.content.Context;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.google.android.material.tabs.TabLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentPowerBinding;
import com.sgb.kjwl.di.home.DaggerHomeFragComponent;
import com.sgb.kjwl.di.home.HomeFragModule;
import com.sgb.link.entity.AreaEntity;
import com.sgb.kjwl.model.entity.BuildPowerTypeEntity;
import com.sgb.jicai.entity.FilterEntity;
import com.sgb.kjwl.model.entity.PowerEntity;
import com.sgb.kjwl.model.entity.ProvinceEntity;
import com.sgb.kjwl.view.event.ChooseAreaEvent;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.ui.activity.MainActivity;
import com.sgb.kjwl.view.ui.activity.power.PowerActivity;
import com.sgb.kjwl.view.ui.adapter.power.PowerListAdapter;
import com.sgb.kjwl.view.widget.BuildPowerPopWindow;
import com.sgb.kjwl.viewmodel.home.PowerFragModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

/**
 * Description:建设力量fragment
 * Author chenfangkai
 */
public class PowerFragment extends AppFragment implements BasePopWindow.OnResultClick {
    public static final String KEY_TYPE = "type";
    private MainActivity activity;
    private boolean isChooice = false;
    private boolean isChange = false;
    private FragmentPowerBinding binding;
    private PowerListAdapter adapter;
    private BuildPowerPopWindow powerPopWindow;
    private List<AreaEntity> areaEntityList;
    private List<BuildPowerTypeEntity> buildPowerTypeEntityList;
    private List<FilterEntity> filterEntityList;
    private Map map;
    private int position;
    private String areaCode;
    @Inject
    PowerFragModel viewModel;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof MainActivity) {
            activity = (MainActivity) context;
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_power, container, false);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();
        initView();
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeFragComponent.builder()
                .appComponent(appComponent)
                .homeFragModule(new HomeFragModule(this))
                .build()
                .inject(this);
    }

    public static PowerFragment newInstance(String type) {
        PowerFragment fragment = new PowerFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_TYPE, type);
        fragment.setArguments(bundle);
        return fragment;
    }

    private void initView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.imgLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isChooice) {
                    viewModel.getPowerAreaList(areaCode + "");
                    isChooice = false;
                } else {
                    if (areaEntityList != null) {
                        showAreaPop();
                    } else {
                        viewModel.getPowerAreaList(areaCode + "");
                    }
                }
            }
        });
        if (adapter == null) {
            adapter = new PowerListAdapter(getActivity(), null);
        }
        binding.rlvList.setLayoutManager(layoutManager);
        binding.rlvList.addItemDecoration(new RecyclerCustomDecoration(0,
                0,
                0,
                getActivity().getResources().getDimension(R.dimen.dp5), getActivity().getResources().getColor(R.color.color_line)));
        binding.rlvList.setAdapter(adapter);
        adapter.setOnItemClick(new AdapterOnItemClick<PowerEntity>() {
            @Override
            public void onItemClick(PowerEntity powerEntity, int position) {
                PowerActivity.start(getActivity(), powerEntity.getNo());

//                WebEvent webEvent = new WebEvent();
//                String url = "http://jsll.m.shigongbang.com/jslldetail?no=" + powerEntity.getNo() + "&address=NAN" + "&personums=" + powerEntity.getPersonums() + "&achivenums=" + powerEntity.getAchivenums();
//                webEvent.setMessageData(url);
//                webEvent.setMessageTag(EventConstant.EVENT_WEBVIEW);
//                EventBus.getDefault().postSticky(webEvent);
//                WebActivity.start(getActivity());
//                Log.i("TabLayout", url);

//                http://jsll.m.shigongbang.com/jslldetail?no=%@&address=%@&personums=%ld&achivenums=%ld
            }
        });

        binding.rlvList.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                viewModel.getPowerList(map);
            }

            @Override
            public void onLoadMore() {
                viewModel.getPowerListMore(map);
            }
        });

        powerPopWindow = new BuildPowerPopWindow(getActivity());
        powerPopWindow.setBgView(binding.grayLayout);
        powerPopWindow.setOnResultClick(this);
        binding.tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                Log.i("TabLayout", "第一次选中" + tab.getPosition());
                isChange = true;
                position = tab.getPosition();
                map.put("categoryNo", buildPowerTypeEntityList.get(tab.getPosition()).getNo());
                viewModel.getPowerList(map);
                viewModel.getPowerAttributesList(buildPowerTypeEntityList.get(position).getNo());
                viewModel.getRecordEnters();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                Log.i("TabLayout", "再次选中");
            }
        });
    }

    private void init() {
        map = new HashMap();
        areaCode = viewModel.getProvinceCodeModel();
        viewModel.getPowerTypeList();
    }

    public void showAreaPop(List<AreaEntity> datas) {
        this.areaEntityList = datas;
        showAreaPop();
    }

    private void showAreaPop() {
        powerPopWindow.showPopwindow(binding.imgLl);
        powerPopWindow.setData(areaEntityList, filterEntityList);
        powerPopWindow.setChildView(filterEntityList, isChange);
        isChange = false;
    }

    public void getFilterList(List<FilterEntity> filterEntityList) {
        this.filterEntityList = filterEntityList;
//        powerPopWindow.setChildView(filterEntityList);
    }


    public void initTypeList(List<BuildPowerTypeEntity> buildPowerTypeEntityList) {
        this.buildPowerTypeEntityList = buildPowerTypeEntityList;
        for (BuildPowerTypeEntity buildPowerTypeEntity : buildPowerTypeEntityList) {
            binding.tablayout.addTab(binding.tablayout.newTab().setText(buildPowerTypeEntity.getName()));
        }
    }

    public void refresh(List<PowerEntity> datas) {
        binding.emptyView.setVisibility(View.GONE);
        binding.rlvList.setVisibility(View.VISIBLE);
        binding.rlvList.setLoadingMoreEnabled(true);
        adapter.setDatas(datas);
        binding.rlvList.refreshComplete();
        if (adapter.getItemCount() >= viewModel.total) {
            binding.rlvList.setLoadingMoreEnabled(false);
        }
    }

    public void loadMore(List<PowerEntity> datas) {
        adapter.addDatas(datas);
        binding.rlvList.loadMoreComplete();
        if (adapter.getItemCount() >= viewModel.total) {
            binding.rlvList.setLoadingMoreEnabled(false);
        }
    }

    public void empty() {
        binding.rlvList.refreshComplete();
        binding.rlvList.setVisibility(View.GONE);
        binding.emptyView.setVisibility(View.VISIBLE);
    }

    public void loadMoreComplete() {
        binding.rlvList.loadMoreComplete();
    }

    @Override
    public void result(Object key1, Object key2,Object key3) {
        List<String> noList = (List<String>) key2;
        map.put("cityCode", (String) key1);
        map.put("attributes", noList);
        viewModel.getPowerList(map);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (powerPopWindow != null && powerPopWindow.isShowing()) {
            powerPopWindow.dismiss();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(ChooseAreaEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_CHOOSE_AERA) {
            //todo 城市切换暂时注释1
            ProvinceEntity<List<ProvinceEntity>> list = (ProvinceEntity<List<ProvinceEntity>>) event.getMessageData();
            areaCode = list.getId() + "";
            isChooice = true;
        }
    }
}
